我有一个文件如下:

line1
line2
line3

我想要得到:

prefixline1
prefixline2
prefixline3

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

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


当前回答

使用&(与模式"匹配的整个输入部分):

cat in.txt | sed -e "s/.*/prefix&/" > out.txt

或者使用反向引用:

cat in.txt | sed -e "s/\(.*\)/prefix\1/" > out.txt

其他回答

使用Pythonize (pz):

pz '"preix"+s' <filename

下面是一个使用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

使用&(与模式"匹配的整个输入部分):

cat in.txt | sed -e "s/.*/prefix&/" > out.txt

或者使用反向引用:

cat in.txt | sed -e "s/\(.*\)/prefix\1/" > out.txt

下面是一个使用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
SETLOCAL ENABLEDELAYEDEXPANSION

YourPrefix=blabla

YourPath=C:\path

for /f "tokens=*" %%a in (!YourPath!\longfile.csv)     do (echo !YourPrefix!%%a) >> !YourPath!\Archive\output.csv