user2914606
user2914606

Reputation: 71

Replace 2nd occurance of a special character after nth occurance of a delimiter from string,in unix/linux

Here My question is,

Replace 2nd or all occurance of a special character after nth occurance of a delimiter from string,in unix/linux

or

Replace "Text Qualifier" character from data field in unix.

I have below string where '"'(Double Quote) should get replaced with space.

String:

"123"~"23"~"abc"~24.50~"descr :- nut size 12" & bolt size 12"1/2, Quantity=20"~"2013-03-13"

From above string, i want below output:

"123"~"23"~"abc"~24.50~"descr :- nut size 12  & bolt size 12 1/2, Quantity=20"~"2013-03-13"

I have replaced " double quote character with space character.

"descr :- nut size 12" & bolt size 12"1/2, Quantity=20"

&

"descr :- nut size 12  & bolt size 12 1/2, Quantity=20"

I want to identify such rows from file & would like to replace such text qualifier character from data in Unix/Linux.

Request you to provide your inputs, & thanking you in advance.

Upvotes: 0

Views: 369

Answers (2)

Alfe
Alfe

Reputation: 59516

I would use plain read to get the fields and then modify the wished ones using sed or shell variable substitution mechanisms:

echo '"123"~"23"~"abc"~24.50~"descr :- nut size 12" & bolt size 12"1/2, Quantity=20"~"2013-03-13"' | {
  IFS='~' read a b c d e f
  printf "%s~%s~%s~%s~%s~%s" "$a" "$b" "$c" "$d" "$(sed 's/"/ /g' <<<$e)" "$f"
  # or:
  printf "%s~%s~%s~%s~%s~%s" "$a" "$b" "$c" "$d" "${e//\"/ }" "$f"
}

That IFS ("Internal Field Separator") is an internal variable telling the shell how to separate fields, e.g. when using read. In our case using this tells the shell to use ~ as separator. Prepending the assignment directly to the read command makes that assignment only for the duration of the read command.

Upvotes: 1

Sven
Sven

Reputation: 1768

I'm going to assume you work in the bash shell.

awk(awk) can help you split your input string at the right positions, using its "-F" option:

echo xyzabcdef | awk -Fb '{print $1}'

gives you "xyza", the the first string before the separator.

Then, the tr(1) utility can help you replace characters:

tr '"' ' '

will replace '"' with ' '. I hope this helps to get you in the right direction.

Upvotes: 0

Related Questions