繁体   English   中英

如何在bash文件夹中的每个文件的开头添加一个字符串?

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

我希望能够将字符串前置到文件夹中每个文本文件的开头。 如何在Linux上使用bash执行此操作?

这样做会。 如果您对每个文件执行相同的文本,则可以提高效率...

for f in *; do 
  echo "whatever" > tmpfile
  cat $f >> tmpfile
  mv tmpfile $f
done

你可以这样做,没有循环和cat

sed -i '1i whatever' *

如果要备份文件,请使用-i.bak

或者使用awk

awk 'FNR==1{$0="whatever\n"$0;}{print $0>FILENAME}' *

你也可以在1个单一命令中使用sed来做到这一点

for f in *; do
  sed -i.bak '1i\
  foo-bar
  ' ${f}
done

这是我最容易解决的问题。

sed -i '1s/^/Text添加然后新file\\n/' /file/to/change

这是一个例子:

for f in *; 
do
    mv "$f" "whatever_$f"
done

这应该可以解决问题。

FOLDER='path/to/your/folder'
TEXT='Text to prepend'
cd $FOLDER
for i in `ls -1 $FOLDER`; do
     CONTENTS=`cat $i`
     echo $TEXT > $i  # use echo -n if you want the append to be on the same line
     echo $CONTENTS >> $i
done

如果您的文件非常大,我不建议这样做。

你也可以这样做:

for f in *; do
  cat <(echo "someline") $f > tempfile
  mv tempfile $f
done

它与第一篇文章没什么不同,但确实展示了如何将'echo'语句的输出视为文件而不必创建临时文件来存储值。

如果您愿意,可以使用ed命令执行不带临时文件:

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

单行: rename '' string_ *

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM