I am trying to increment a value in a csv file, provided it matches a search string. Here is the script that was utilized:
awk -i inplace -F',' '$1 == "FL" { print $1, $2 1} ' data.txt
Contents of data.txt:
NY,1
FL,5
CA,1
Current Output:
FL 6
Intended Output:
NY,1
FL,6
CA,1
Thanks.
CodePudding user response:
$ awk 'BEGIN{FS=OFS=","} $1=="FL"{ $2} 1' data.txt
NY,1
FL,6
CA,1
CodePudding user response:
Intended Output:
NY,1 FL,6 CA,1
I would harness GNU AWK
for this task following way, let file.txt
content be
NY,1
FL,5
CA,1
then
awk 'BEGIN{FS=OFS=",";ORS=" "}{print $1,$2 ($1=="FL")}' file.txt
gives output
NY,1 FL,6 CA,1
Explanation: I inform GNU AWK
that field separator (FS
) and output field separator (OFS
) is ,
and output row separator (ORS
) is space with accordance to your requirements. Then for each line I print
1st field followed by 2nd field increased by is 1st field FL? with 1 denoting it does hold, 0 denotes it does not hold. If you want to know more about FS
or OFS
or ORS
then read 8 Powerful Awk Built-in Variables – FS, OFS, RS, ORS, NR, NF, FILENAME, FNR
(tested in gawk 4.2.1)
CodePudding user response:
Use this Perl one-liner:
perl -i -F',' -lane 'if ( $F[0] eq "FL" ) { $F[1] ; } print join ",", @F;' data.txt
The Perl one-liner uses these command line flags:
-e
: Tells Perl to look for code in-line, instead of in a file.
-n
: Loop over the input one line at a time, assigning it to $_
by default.
-l
: Strip the input line separator ("\n"
on *NIX by default) before executing the code in-line, and append it when printing.
-a
: Split $_
into array @F
on whitespace or on the regex specified in -F
option.
-F','
: Split into @F
on comma, rather than on whitespace.
-i.bak
: Edit input files in-place (overwrite the input file). Before overwriting, save a backup copy of the original file by appending to its name the extension .bak
. If you want to skip writing a backup file, just use -i
and skip the extension.
SEE ALSO:
perldoc perlrun
: how to execute the Perl interpreter: command line switches