簡體   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