我有一个文件如下:

line1
line2
line3

我想要得到:

prefixline1
prefixline2
prefixline3

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

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


当前回答

如果你的前缀有点复杂,就把它放在一个变量中:

prefix=path/to/file/

然后,你传递这个变量,让awk来处理它:

awk -v prefix="$prefix" '{print prefix $0}' input_file.txt

其他回答

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

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

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

你可以在Ex模式下使用Vim:

ex -sc '%s/^/prefix/|x' file

%选择所有行 年代取代 保存并关闭

下面是一个使用sed方法的示例:

$ cat /path/to/some/file | prefix_lines "WOW: "

WOW: some text
WOW: another line
WOW: more text

prefix_lines

function show_help()
{
  IT=$(CAT <<EOF
    Usage: PREFIX {FILE}

    e.g.

    cat /path/to/file | prefix_lines "WOW: "

      WOW: some text
      WOW: another line
      WOW: more text
  )
  echo "$IT"
  exit
}

# Require a prefix
if [ -z "$1" ]
then
  show_help
fi

# Check if input is from stdin or a file
FILE=$2
if [ -z "$2" ]
then
  # If no stdin exists
  if [ -t 0 ]; then
    show_help
  fi
  FILE=/dev/stdin
fi

# Now prefix the output
PREFIX=$1
sed -e "s/^/$PREFIX/" $FILE

你可以用AWK来做

echo example| awk '{print "prefix"$0}'

or

awk '{print "prefix"$0}' file.txt > output.txt

对于后缀:awk '{打印$0"后缀"}'

对于前缀和后缀:awk '{打印“前缀”$0“后缀”}'

在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