linux用另一个字符串替换字符串

时间:2016-10-25 13:07:03

标签: linux string bash replace sed

我想替换文件中的字符串。 我有一个文本文件,如下所示:id#string。

123456#some new string
234567#some other new string
345678#still some other new string

然后我有很多基于文本文件ID的文件夹。

所以现在我想替换文本文件中的字符串

{"fields":[{"t":"B","v":"false or true","n":"SomeText"},{"t":"S","v":"","n":"Keywords"},{"t":"S","v":"","n":"Author"},{"t":"S","v":"","n":"SomeText"},{"t":"S","v":"THI$ is THE old §TRING I want to REPLACE","n":"SomeText"},{"t":"S","v":"","n":"SomeText"},{"t":"A","n":"SomeText"},{"t":"A","v":"SomeInt","n":"SomeText"}]}

但我不知道怎么做,因为newstring和/或oldstring可能包含其他字符

#!/bin/bash
FOLDER=`echo 123456#string | cut -d# -f1`
NEWSTRING=`echo 123456#string | cut -d# -f2`
sed -i ??? $FOLDER/filename.txt

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

问题尚不明确应该采取什么措施以及取代什么,但也许你需要的是:

#!/bin/bash
#
# t1 file contains your strings
#

ROW='{"fields":[{"t":"B","v":"false or true","n":"SomeText"},{"t":"S","v":"","n":"Keywords"},{"t":"S","v":"","n":"Aut
IFS=$'\n'
for S in $(cat ./t1); do
    F=$(echo $S | awk -F# '{print $1}')
    N=$(echo $S | awk -F# '{print $2}')
    if [ -z "$N" ]; then continue; fi
    NROW=$(echo ${ROW/THIS is THE old STRING I want to REPLACE/$S})
    NROW=$(echo ${NROW/Keywords/$N})
    NROW=$(echo ${NROW/false or true/$F})
    #mkdir $F
    #echo $NROW >> file.json
    echo $NROW 
done