i have the following problem at work:
we have a xml file from which we read infos like hostname, address and os via xmlstarlet and redirect them into a separate file.
this is the Script:
xmlstarlet sel -t -m "//host" -m "hostnames/hostname" -v "@name" -b -o "|" -v "address[@addrtype='ipv4']/@addr" -o "|" -v "os/osmatch[1]/@name" -n nmap.xml > newfile
now we have 3 infos each line separated by a | like
imahost|192.168.50.6|windows
some servers do not have a hostname but only the ip and the os like
|192.168.50.7|windows
then we cut the hostname and the ip out from the file where f1 is hostname and f2 is ip like:
cat newfile | cut -d"|" -f1,2
it looks like this
imahost|192.168.50.6 |192.168.50.7 ...
if a hostname is not available as in the second line the ip should be inserted in the first position like
imahost|192.168.50.6 192.168.50.7|192.168.50.7 ...
how do we do this? ^^
i thank you in advance for every helpful answer
awk
can handle empty columns:
awk 'BEGIN{FS=OFS="|"} $1==""{$1=$2} {print $1,$2}' file
Set input and output field separator to |
. If first column is empty copy content of second column to first column. In any case print first and second row.
Output:
imahost|192.168.50.6 192.168.50.7|192.168.50.7
See: 8 Powerful Awk Built-in Variables – FS, OFS, RS, ORS, NR, NF, FILENAME, FNR