
Question:
with input csv file
sid,storeNo,latitude,longitude 2,1,-28.03720000,153.42921670 9I wish to output only the lines with one column, in this example it's line 3. how can this be done in bash shell script?
Answer1:<strong>Using awk</strong>
The following awk would be usfull
$ awk -F, 'NF==1' inputFile
9
<strong>What it does?</strong>
<ul><li>-F,
sets the field separator as ,
NF==1
matches lines with NF
, number of fields as 1. No action is provided hence default action, printing the entire record is taken. it is similar to NF==1{print $0}
inputFile
input csv file to the awk script
<strong>Using grep</strong>
The same function can also be done using grep
$ grep -v ',' inputFile
9
<ul><li>-v
option prints lines that do not match the pattern
,
along with -v
greps matches lines that do not contain ,
field separator
<strong>Using sed</strong>
$ sed -n '/^[^,]*$/p' inputFile
9
<strong>what it does?</strong>
<ul><li>-n
suppresses normal printing of pattern space
'/^[^,]*$/
selects lines that match the pattern, lines without any ,
^
anchors the regex at the start of the string
[^,]*
matches anything other than ,
$
anchors string at the end of string
p
action p
makes sed to print the current pattern space, that is pattern space matching the input
try this bash
script
#!/bin/bash
while read -r line
do
IFS=","
set -- $line
case ${#} in
1) echo $line;;
*) continue;;
esac
done < file