How can I add a string to the beginning of each file in a folder in bash?

前端 未结 9 869
天命终不由人
天命终不由人 2021-01-01 17:04

I want to be able to prepend a string to the beginning of each text file in a folder. How can I do this using bash on Linux?

相关标签:
9条回答
  • 2021-01-01 17:29

    This will do that. You could make it more efficient if you are doing the same text to each file...

    for f in *; do 
      echo "whatever" > tmpfile
      cat $f >> tmpfile
      mv tmpfile $f
    done
    
    0 讨论(0)
  • 2021-01-01 17:38

    You may use the ed command to do without temporary files if you like:

    for file in *; do
      (test ! -f "${file}" || test ! -w "${file}") && continue                # sort out non-files and non-writable files
      if test -s "${file}" && ! grep -Iqs '.*' "${file}"; then continue; fi   # sort out binary files
      printf '\n%s\n\n' "FILE:  ${file}"
      # cf. http://wiki.bash-hackers.org/howto/edit-ed
      printf '%s\n' H 0a "foobar" . ',p' q | ed -s "${file}"  # dry run (just prints to stdout)
      #printf '%s\n' H 0a "foobar" . wq | ed -s "${file}"     # in-place file edit without any backup
    done | less
    
    0 讨论(0)
  • 2021-01-01 17:39

    You can do it like this without a loop and cat

    sed -i '1i whatever' *
    

    if you want to back up your files, use -i.bak

    Or using awk

    awk 'FNR==1{$0="whatever\n"$0;}{print $0>FILENAME}' *
    
    0 讨论(0)
提交回复
热议问题