Add the file name to the beginning of the file using find and sed

using the following: I add the file name at the beginning of each line and send the output to one file.

ls | while read file; do sed -e "s/^/$file/g" $file > out; done

I want to do the same replacement sed, but using the commands findand execor xargs-

find . -type f -exec sed "s/^/{}/g" {} > out +

but I get an error -

find: only one instance {} is supported with -exec ... +

The input files are as follows:

fileA.txt

A1
A2

fileB.txt

B1
B2

desired output

fileA.txt A1
fileA.txt A2
fileB.txt B1
fileB.txt B2

I know how to do this with awk, but I would like to do it with sed, find and exec or xargs.

+3
source share
4 answers
 find . -type f |xargs awk '$0=FILENAME$0' > out

as I replied, your string "no awk" does not exist yet. anyway, see my updated answer below:

find, exec/xargs sed . script GNU Sed, , .

: (, > out . .)

find . -type f | xargs -i echo {}|sed -r 's#(.\/)(.*)#cat &\|sed  "s:^:file \2 :g"#ge'

, . :

kent$  head *.txt
==> a.txt <==
A1
A2

==> b.txt <==
B1
B2

kent$  find . -type f | xargs -i echo {}|sed -r 's#(.\/)(.*)#cat &\|sed  "s:^:file \2 :g"#ge'
file b.txt B1
file b.txt B2
file a.txt A1
file a.txt A2

- ?

  • find ....|xargs -i echo {} , ( "./")
  • sed, sed -r 's#(.\/)(.*)# MAGIC #ge'
  • , \1: "./" \2 "a.txt"(filename)
  • sed e, MAGIC . ( GNU sed)
  • MAGIC: cat &\|sed "s:^:file \2 :g cat sed. (s:..:..:g)
  • , MAGIC sed.

- "e" Gnu sed.

+4

untested, xargs

find . -type f | xargs -I FILE sed "s/^/FILE/g" FILE > out
+4

ls find ?

find . -type f | while read file; do sed -e "s|^|$file|" $file > out; done

s / , . |.

+1

:

find . -type f | xargs -i echo FILE/{} > out
0

Source: https://habr.com/ru/post/1528185/


All Articles