繁体   English   中英

如何使用 bash 脚本和 sed 用换行符替换字符串?

[英]How do I replace a string with a newline using a bash script and sed?

我有以下输入:

Value1|Value2|Value3|Value4@@ Value5|Value6|Value7|Value8@@ Value9|etc...

在我的 bash 脚本中,我想用换行符替换@@ 我用 sed 尝试了各种方法,但我没有任何运气:

line=$(echo ${x} | sed -e $'s/@@ /\\\n/g')

最终我需要将整个输入解析为行和值。 也许我的做法是错误的。 我打算用换行符替换@@ ,然后通过设置IFS='|'循环输入拆分值。 如果有更好的方法请告诉我,我仍然是 shell 脚本的初学者。

这将工作

sed 's/@@ /\n/g' filename

用新行替换@@

使用纯 BASH 字符串操作:

eol=$'\n'
line="${line//@@ /$eol}"

echo "$line"
Value1|Value2|Value3|Value4
Value5|Value6|Value7|Value8
Value9|etc...

我建议使用tr函数

echo "$line" | tr '@@' '\n'

例如:

[itzhaki@local ~]$ X="Value1|Value2|Value3|Value4@@ Value5|Value6|Value7|Value8@@"
[itzhaki@local ~]$ X=`echo "$X" | tr '@@' '\n'`
[itzhaki@local ~]$ echo "$X"
Value1|Value2|Value3|Value4

 Value5|Value6|Value7|Value8

如果您不介意使用 perl:

echo $line | perl -pe 's/@@/\n/g'
Value1|Value2|Value3|Value4
 Value5|Value6|Value7|Value8
 Value9|etc

终于让它与:

sed 's/@@ /'\\\n'/g'

无论出于何种原因,在 \\\\n 周围添加单引号似乎都有帮助

怎么样:

for line in `echo $longline | sed 's/@@/\n/g'` ; do
    $operation1 $line
    $operation2 $line
    ...
    $operationN $line
    for field in `echo $each | sed 's/|/\n/g'` ; do
        $operationF1 $field
        $operationF2 $field
        ...
        $operationFN $field
    done
done

这结束了使用 perl 来完成它,并提供了一些简单的帮助。

$ echo "hi\nthere"
hi
there

$ echo "hi\nthere" | replace_string.sh e
hi
th
re

$ echo "hi\nthere" | replace_string.sh hi


there

$ echo "hi\nthere" | replace_string.sh hi bye
bye
there

$ echo "hi\nthere" | replace_string.sh e super all
hi
thsuperrsuper

替换字符串.sh

#!/bin/bash

ME=$(basename $0)
function show_help()
{
  IT=$(cat <<EOF

  replaces a string with a new line, or any other string, 
  first occurrence by default, globally if "all" passed in

  usage: $ME SEARCH_FOR {REPLACE_WITH} {ALL}

  e.g. 

  $ME :       -> replaces first instance of ":" with a new line
  $ME : b     -> replaces first instance of ":" with "b"
  $ME a b all -> replaces ALL instances of "a" with "b"
  )
  echo "$IT"
  exit
}

if [ "$1" == "help" ]
then
  show_help
fi
if [ -z "$1" ]
then
  show_help
fi

STRING="$1"
TIMES=${3:-""}
WITH=${2:-"\n"}

if [ "$TIMES" == "all" ]
then
  TIMES="g"
else
  TIMES=""
fi

perl -pe "s/$STRING/$WITH/$TIMES"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM