简体   繁体   中英

Bash: how to read a multiple lines into another file, while replacing delims and truncating after token $n

What I'm trying to do is change the format of one particular file into another:

input.csv:

value1,value2,value3,value4,value5,value6

output.txt:

value2:value3

I can almost do this using the following, but it all gets read out on the same line, rather than out to multiple:

output=$(while IFS="," read -r value1 value2 value3 remainder; do echo $value2:$value3 ; done < "input.csv")
echo $output > output.txt

solved my own issue by adding \\ at the end of the echo string

With awk :

awk -F',' '{printf "%s:%s\n", $2, $3}' file.csv

Printing comma separated second and third column with : as the separator.

Example:

% awk -F',' '{printf "%s:%s\n", $2, $3}' <<<'value1,value2,value3,value4,value5,value6'
value2:value3

通过在回显字符串的末尾添加反斜杠“ \\”来解决

If the output variable is not needed for anything else you can save a pid and some grief by removing the command substitution

while IFS=',' read -r value1 value2 value3 remainder; do
  echo "$value2:$value3"
done

A more robust and general way to process csv input is to use awk as shown at https://www.gnu.org/software/gawk/manual/html_node/Splitting-By-Content.html

awk 'BEGIN {FPAT="([^,]*)|(\"[^\"]+\")"; OFS=":"} {print $2,$3}'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM