我有一个文件如下:

line1
line2
line3

我想要得到:

prefixline1
prefixline2
prefixline3

我可以编写Ruby脚本,但如果我不需要这样做会更好。

前缀将包含/。为路径,例如“/opt/workdir/”。


当前回答

下面是一个使用moreutils的ts命令的高可读性的联机解决方案

$ cat file | ts prefix | tr -d ' '

以及它是如何一步步推导出来的:

# Step 0. create the file

$ cat file
line1
line2
line3
# Step 1. add prefix to the beginning of each line

$ cat file | ts prefix
prefix line1
prefix line2
prefix line3
# Step 2. remove spaces in the middle

$ cat file | ts prefix | tr -d ' '
prefixline1
prefixline2
prefixline3

其他回答

下面是一个使用moreutils的ts命令的高可读性的联机解决方案

$ cat file | ts prefix | tr -d ' '

以及它是如何一步步推导出来的:

# Step 0. create the file

$ cat file
line1
line2
line3
# Step 1. add prefix to the beginning of each line

$ cat file | ts prefix
prefix line1
prefix line2
prefix line3
# Step 2. remove spaces in the middle

$ cat file | ts prefix | tr -d ' '
prefixline1
prefixline2
prefixline3

如果你有Perl:

perl -pe 's/^/PREFIX/' input.file

对于使用BSD/OSX系统的人来说,有一个实用程序叫做lam,是laminate的缩写。Lam -s前缀文件将做你想做的。我把它用在管道上,例如:

查找type f -exec lam -s "{}: " "{}" \;| fzf

...这将找到所有的文件,exec lam对他们每个,给每个文件自己的文件名的前缀。(并将输出泵到fzf进行搜索。)

在bash的命令行上使用for循环的简单解决方案:

for i in $(cat yourfile.txt); do echo "prefix$i"; done

将输出保存到一个文件:

for i in $(cat yourfile.txt); do echo "prefix$i"; done > yourfilewithprefixes.txt

如果您需要在每行具有特定字符串的开头预先添加文本,请尝试以下操作。在下面的例子中,我在每一行有“rock”的行开始添加#。

sed -i -e 's/^.*rock.*/#&/' file_name