简体   繁体   English

Bash用变量替换字符串中的第N个单词

[英]Bash replace Nth word in a string with a variable

I need to find Nth word in a string (space delimited) and replace with a variable. 我需要在字符串(以空格分隔)中找到第N个单词,并用一个变量替换。 In the below example 4th word needs to be replaced with another string. 在下面的示例中,第四个单词需要用另一个字符串替换。

1 Test 123456 REPLACE_ME 99

to

1 Test 123456 $STRING_TO_REPLACE 99

I was able to find 4th word using awk '{ print $4}' , but don't know how to replace with another string variable. 我能够使用awk '{ print $4}'找到第四个单词,但不知道如何用另一个字符串变量替换。

Any help will be much appreciated. 任何帮助都感激不尽。

   replace='replace me'; echo "233131 2 saad four five dssd sdad" |  awk -v r="$replace" '{ for(i = 1; i <= NF; i++) { if ( i == 4 )print r;else print $i } }'

using awk 使用awk

str="1 Test 123456 REPLACE_ME 99"
STRING_TO_REPLACE="Hello"

echo $str |awk -v r=${STRING_TO_REPLACE} '{$4=r}1'

Here are two shell solutions. 这是两个外壳解决方案。 The first is a pure sh solution: 第一个是纯sh解决方案:

set -- 1 Test 123456 REPLACE_ME 99
one=$1
two=$2
three=$3
shift 4
echo $one $two $three '$STRING_TO_REPLACE' $*

The output is: 输出为:

1 Test 123456 $STRING_TO_REPLACE 99

The second is a bash solution: 第二个是bash解决方案:

set -- 1 Test 123456 REPLACE_ME 99
echo ${*:1:3} '$STRING_TO_REPLACE' ${*:5:$#}

This outputs: 输出:

1 Test 123456 $STRING_TO_REPLACE 99

If you want to replace the N-th word, you could do like this: 如果要替换第N个字,可以这样:

awk -v n=4 -v r="$STRING_TO_REPLACE" '{ $n = r } 1' <<< "$str"

Using GNU sed you could replace the 4th word like this: 使用GNU sed,您可以这样替换第四个单词:

str="1 Test 123456 REPLACE_ME 99"
STRING_TO_REPLACE="Hello"
sed -e "s/\<\w\+/STRING_TO_REPLACE/4" <<< "$str"

The pattern there means: 那里的模式意味着:

  • \\< -- start of word \\< -词的开头
  • \\w -- "word character" \\w “文字字符”
  • \\+ -- one or more of the previous match \\+ -上一场比赛中的一项或多项
  • \\w\\+ -- one or more word characters \\w\\+ -一个或多个单词字符
  • The 4 in s///4 means to perform the replacement for the 4th occurrence only s///4 4s///4表示仅对第4个事件进行替换

Another pure sh (possibly bash) solution 另一种纯sh(可能是bash)解决方案

set -- 1 Test 123456 REPLACE_ME 99
set -- "${@:0:4}" SOMETHING_ELSE "${@:5}"

if you have Ruby 如果你有露比

# echo "1 Test 123456 REPLACE_ME 99" | ruby -e 'f=gets.split(/\s+/);f[3]="new";puts f.join(" ")'
1 Test 123456 new 99

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

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