-3

I'm trying to find how to replace text in the following format:

input1:input2:input3
aaa:bbb:ccc
111:222:333

I would like the result to look like:

input1:new-text:input3
aaa:new-text:ccc
111:new-text:333

It can be accomplished via sed, awk, cut or what ever as long as the result is good.

  • 1
    What have you tried? Googling sed would give you the answer very quickly. – Nasir Riley Sep 1 '18 at 20:31
0

Given the rule "replace the second field, delimited by colons with new-text", awk makes this fairly straight-forward:

awk -F':' 'BEGIN { OFS=FS } {$2="new-text"; print} ' < input > output

The -F':' tells awk to use colons to separate fields within each line.

The BEGIN stanza sets the output field separator to the current field separator (colon), so that when we re-print the line later, awk joins the fields together with colons again.

The second section has no conditional in front of it, so it is executed for every line; it does the actual work of replacing the second field with new-text, then prints the new line.

  • 1
    Awesome!! Exactly what I wanted. Keeping this in my notes as a bash coder newbie :) – John Doe Sep 1 '18 at 20:50
  • 1
    Glad it helped! Note that there's nothing "bash" about this! – Jeff Schaller Sep 1 '18 at 20:51
0

if you really need exactly the same text to replace middle chunk between the only surrounding pair of ':' on every line of file then this works

sed -i -- "s|:.*:|:${mynewtext}:|"   $inputfile

the pattern .* just means one or more characters

0

Let's say that your text is in file called code

]$cat code
input1:input2:input3
aaa:bbb:ccc
111:222:333

run this command

]$sed -e 's/:[^:]*:/:new-text:/' code
input1:new-text:input3
aaa:new-text:ccc
111:new-text:333
0

To look at it in a generic and POSIX sed way, wherein the column to be removed can be supplied at the time of executing the sed code, as also the new contents of the column to be replaced also, you may do this:

n=2;             # the column number to be modified with a new value

repl="new-text"; # the text used to replace the contents of the n-th col

# to make the replacement sed friendly, otw, if it happened to have chars
# which have a meaning to sed when using on the rhs of s/// command, we will
# have an error on our hands.
repl_esc=$(printf '%s\n' "$repl" | sed -e 's|[\&/]|\\&|g;$!s/$/\\/')

sed -e '
    s/.*/:&:/
    '"s/:/\\n/$n;s//\\
/$n;
    s/\\n.*\\n/:${repl_esc}:/"'
    s/^://
    s/:$//
' input-file.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.