add filename to beginning of file using find and sed

后端 未结 5 648
死守一世寂寞
死守一世寂寞 2021-01-04 23:51

using the following I add the file name to the front of each line and send the output to a single file.

ls | while read file; do sed -e \"s/^/$file/g\" $fil         


        
相关标签:
5条回答
  • 2021-01-05 00:21

    Why don't you simply replace the ls in your first line with the find like this?

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

    You must only exchange the delimiter for s from / to something else not contained in your filenames. I have chosen | as an example.

    0 讨论(0)
  • 2021-01-05 00:23

    this one works fine for me and it is simpler to use than Kent's answer
    NOTE: than the full pathname is inserted for that one

    find . -type f | xargs -r -t -i sed -r 's|^|'{}' |g' {}
    

    use this one instead to keep only the bare filename part

    find . -type f | xargs -r -t -i sed -r -e 's|^|'{}' |g' -e 's|^.+/||g' {}
    

    then if your are happy with stdout results you might add -i switch to the sed command to overwrite the files

    find . -type f | xargs -r -t -i sed -i -r -e 's|^|'{}' |g' -e 's|^.+/||g' {}
    
    0 讨论(0)
  • 2021-01-05 00:30

    How about:

    find . -type f | xargs -i echo FILE/{} > out
    
    0 讨论(0)
  • 2021-01-05 00:33

    untested, try using xargs

    find . -type f | xargs -I FILE sed "s/^/FILE/g" FILE > out
    
    0 讨论(0)
  • 2021-01-05 00:36
     find . -type f |xargs awk '$0=FILENAME$0' > out
    

    as I answered this, your "no awk" line not yet there. anyway, take a look my updated answer below:

    updated based on comment

    so you want to use find, exec/xargs, and sed to do it. My script needs GNU Sed, i hope you have it.

    see the one liner first: (well, > out is omitted. You could add it to the end of the line. )

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

    now let's take a test, see below:

    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
    

    is the result your expectation?

    Short explanation

    • find ....|xargs -i echo {} nothing to explain, just print the filename per line (with leading "./")
    • then pass the filename to a sed line like sed -r 's#(.\/)(.*)# MAGIC #ge'
    • remember that in the above line, we have two groups \1: "./" and \2 "a.txt"(filename)
    • since we have e at the end of sed line, the MAGIC part would be executed as shell command.(GNU sed needed)
    • MAGIC: cat &\|sed "s:^:file \2 :g cat & is just output the file content, and pipe to another sed. do the replace (s:..:..:g)
    • finally, the execution result of MAGIC would be the Replacement of the outer sed.

    the key is the 'e' of Gnu sed.

    0 讨论(0)
提交回复
热议问题