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

ecfsfe2w  于 2023-04-21  发布在  Shell
关注(0)|答案(7)|浏览(216)

我有以下输入:

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

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

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

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

q0qdq0h2

q0qdq0h21#

使用纯BASH字符串操作:

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

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

或者在单步中执行:

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

nkcskrwz2#

这会有用的

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

用新行替换@@

3mpgtkmj

3mpgtkmj3#

我建议使用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
gev0vcfq

gev0vcfq4#

终于让它工作了:

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

在\n周围添加单引号似乎出于某种原因有所帮助

guicsvcw

guicsvcw5#

如果你不介意使用Perl:

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

eoxn13cs6#

怎么样:

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
cngwdvgl

cngwdvgl7#

这就结束了使用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

replace_string.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"

相关问题