shantanuo
shantanuo

Reputation: 32296

changing values from specific columns

The following sed command is working as expected. What I need to do is to change the null (\n) to 0 only in the second column.

# cat nulltest.txt 
1   abc
1   \N
\N  xyz

# sed 's/\\N/0/' nulltest.txt 
1   abc
1   0
0   xyz

Expected results :

1   abc
1   0
\N  xyz

Data is separated by tab "\t"

Upvotes: 0

Views: 743

Answers (3)

Vaman Kulkarni
Vaman Kulkarni

Reputation: 3451

You could use below regex in your sed expression which ensures that \N is in 2nd column.

^([^\t]+\t)\\N(\t)

So your sed expression will look something like below

sed -r -i 's/^([^\t]+\t)\\N(\t)/\10\2/g' nulltest.txt

Explanation:

^([^\t]+\t): will match 1 followed by \t and () around the regex makes it first group.

\\N : will match \N

(\t): It the tab after second column which is second group.

In the substitue section of sed notice use of \1 and \2 which represents the first and second group from the regex which in your case is 1 followed by \t and \t respectively. So it will keep group one and two and replace rest of the matched string with 0.

In my testing I used below input file

abcdefgh
3   abc \N  \N  \N
123 \N  \N  \N
\N  \Nxyz

and the output I get is

abcdefgh
3   abc \N  \N  \N
123adsa 0   \N  \N
\N  \Nxyz

Notice that exactly \N from 2nd column is replaced. Even if there are any number of columns with \N this sed expression will replace \N only from 2nd column.

Upvotes: 1

Kent
Kent

Reputation: 195029

kent$  echo "1   abc
1   \N
\N  xyz"|awk '{gsub(/\\N/,"0",$2)}1'|column -t
1   abc
1   0
\N  xyz

Upvotes: 2

N4553R
N4553R

Reputation: 188

try this:

sed -r 's/^([^\t]+\t)\\N/\10/' nulltest.txt

Upvotes: 0

Related Questions