Another way to use GNU awk
Single line:
awk '/(^|[ \t]+)-9([ \t]+|$)/{for(i=2; i<=NF; i++)$0=gensub (/[^[:blank:]]+/,-9,i)}1' infile
Better readable:
awk '/(^|[ \t]+)-9([ \t]+|$)/{
for(i=2; i<=NF; i++)
$0=gensub (/[^[:blank:]]+/,-9,i)
}1
' infile
Test results:
Input:
$ cat infile
ID VAR1 VAR2 VAR3 VAR4 VAR5
1 1 1 1 1 1
2 -9 -9 -9 -9 -9
3 3 3 3 3 3
4 4 4 4 -9 4
5 5 5 5 5 5
6 6 -9 6 6 6
Conclusion:
(due to interval shift -
)
$ awk '/(^|[ \t]+)-9([ \t]+|$)/{for(i=2; i<=NF; i++)$0 = gensub (/[^[:blank:]]+/, -9 , i)}1' infile
ID VAR1 VAR2 VAR3 VAR4 VAR5
1 1 1 1 1 1
2 -9 -9 -9 -9 -9
3 3 3 3 3 3
4 -9 -9 -9 -9 -9
5 5 5 5 5 5
6 -9 -9 -9 -9 -9
If you want the result to look better, try this: (not recommended)
awk '/(^|[ \t]+)-9([ \t]+|$)/{for(i=2; i<=NF; i++){ if($i==-9)continue; $0 = gensub (/[^[:blank:]]+/, "\b-9" , i)}}1' infile
ID VAR1 VAR2 VAR3 VAR4 VAR5
1 1 1 1 1 1
2 -9 -9 -9 -9 -9
3 3 3 3 3 3
4 -9 -9 -9 -9 -9
5 5 5 5 5 5
6 -9 -9 -9 -9 -9
More readable version above:
awk '/(^|[ \t]+)-9([ \t]+|$)/{
for(i=2; i<=NF; i++)
{
if($i==-9)continue;
$0 = gensub(/[^[:blank:]]+/, "\b-9" , i)
}
}1
' infile
source
share