如何使用循环将文件开头添加到另一个文件

how to add beginning of file to another file using loop

我有文件 1.txt、2.txt、3.txt 和 1-bis.txt、2-bis.txt、3-bis.txt

cat 1.txt
#ok
#5 
6 
5

cat 2.txt
#not ok
#56
13
56

cat 3.txt
#nothing
#

cat 1-bis.txt
5
4

cat 2-bis.txt
32
24

cat 3-bis.txt

我想在文件“bis”的开头添加以#(来自非 bis 文件)开头的行,以便获得:

cat 1-bis.txt
#ok
#5
5
4

cat 2-bis.txt
#not ok
#56
32
24

cat 3-bis.txt
#nothing
#

我正在考虑使用 grep -P "#" 到 select 带有 # 的行(或者可能 sed -n),但我不知道如何循环文件来解决这个问题

非常感谢您的帮助

您可以使用此解决方案:

for f in *-bis.txt; do
  { grep '^#' "${f//-bis}"; cat "$f"; } > "$f.tmp" && mv "$f.tmp" "$f"
done

如果您只想在文件开头添加 # 行,则使用:

改变

grep '^#' "${f//-bis}"

与:

awk '!/^#/{exit}1' "${f//-bis}"

可以循环遍历?.txt个文件,通过参数展开导出对应的bis-文件名:

for file in ?.txt ; do
    bis=${file%.txt}-bis.txt
    grep '^#' "$file" > tmp
    cat "$bis" >> tmp
    mv tmp "$bis"
done

不需要grep -P,简单的grep就够了。只需添加 ^ 即可仅匹配行首的八角鱼。