如何在同一个文件中打印文件名?

时间:2021-10-20 23:07:35

I have a file with around 5 lines and I want to have the file name printed at the end of every line.

我有一个5行左右的文件,我想在每行末尾打印文件名。

for file in *.txt
do
  sed -i "1s/\$/${file%%.*}/" "$file"
done

The above code only writes file name in first line, I want to have file name in every line.

上面的代码只在第一行写文件名,我希望在每一行都有文件名。

2 个解决方案

#1


2  

The above code only writes file name in first line

上面的代码只在第一行中写入文件名。

This is what the 1 on the beginning of the sed command does: it is an address that selects the lines processed by the command.

这是sed命令开头的1所做的:它是一个选择命令处理的行的地址。

In your case, the s command applies only to the first line (because of 1 in front of the command). Remove the 1 from the command and it will apply to all lines of the file:

在您的示例中,s命令只应用于第一行(因为命令前面有一个)。从命令中删除1,它将应用于文件的所有行:

for file in *.txt
do
  sed -i "s/\$/${file%%.*}/" "$file"
done

Read more about sed at https://www.gnu.org/software/sed/manual/sed.html.
Given that you have already learned sed, typing man sed on your terminal will refresh your memory about its commands.

在https://www.gnu.org/software/sed/manual/sed.html阅读更多有关sed的信息。如果您已经学习过sed,那么在您的终端上键入man sed将刷新您对其命令的记忆。

#2


1  

This is a bit hacky, but it does the trick (bash):

这有点陈腐,但它有一个诀窍(bash):

filename=<filename>; len=$(wc -l $filename | cut -f1 -d' '); for i in $(seq $len); do echo $filename; done | paste $filename -

And this is cleaner, but needs python installed:

这个更简洁,但需要安装python:

python -c "import sys; print('\n'.join(line.rstrip() + '\t' + sys.argv[1] for line in open(sys.argv[1])))" <filename>

#1


2  

The above code only writes file name in first line

上面的代码只在第一行中写入文件名。

This is what the 1 on the beginning of the sed command does: it is an address that selects the lines processed by the command.

这是sed命令开头的1所做的:它是一个选择命令处理的行的地址。

In your case, the s command applies only to the first line (because of 1 in front of the command). Remove the 1 from the command and it will apply to all lines of the file:

在您的示例中,s命令只应用于第一行(因为命令前面有一个)。从命令中删除1,它将应用于文件的所有行:

for file in *.txt
do
  sed -i "s/\$/${file%%.*}/" "$file"
done

Read more about sed at https://www.gnu.org/software/sed/manual/sed.html.
Given that you have already learned sed, typing man sed on your terminal will refresh your memory about its commands.

在https://www.gnu.org/software/sed/manual/sed.html阅读更多有关sed的信息。如果您已经学习过sed,那么在您的终端上键入man sed将刷新您对其命令的记忆。

#2


1  

This is a bit hacky, but it does the trick (bash):

这有点陈腐,但它有一个诀窍(bash):

filename=<filename>; len=$(wc -l $filename | cut -f1 -d' '); for i in $(seq $len); do echo $filename; done | paste $filename -

And this is cleaner, but needs python installed:

这个更简洁,但需要安装python:

python -c "import sys; print('\n'.join(line.rstrip() + '\t' + sys.argv[1] for line in open(sys.argv[1])))" <filename>