김남진
김남진

Reputation: 23

I want to change newline to a string when saving the result of a linux command in a variable

I am trying to write a shell script that reads the system configuration status of linux and saves the result as CSV.

The result to be saved is the hostname, setting criterion ID, and actual setting value.

The most problematic part when saving as csv is the newline.

For example,

#!/bin/bash
hostname='linux01'
id='SRV-01'
result="*result*\n"
result=$result`cat /etc/passwd | head -n 5`

echo "$hostname, $id, $value" >> test.csv

When the above script exists, the CSV format is broken due to newline.

When script result is as below

linux01, SRV-01, *result*
root:x:0:0:root:/root:/bin/zsh
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync

I want to save to csv file this change.

linux01, SRV-01, *result*\nroot:x:0:0:root:/root:/bin/zsh\ndaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin\nbin:x:2:2:bin: /bin:/usr/sbin/nologin\nsys:x:3:3:sys:/dev:/usr/sbin/nologin\nsync:x:4:65534:sync:/bin:/bin/sync

First, I used sed as a test to change \n to \\n, but when outputting with echo, the \n string is changed to newline.

echo `cat /etc/passwd | head -n 5 | sed -z 's/\n/\\\n/g'`

It is saved as a \n string in the variable, but it is judged that "\n" is changed to 0x0a in echo.

Ask if there is a way to change the echo output to the string "\n" instead of newline.

Upvotes: 0

Views: 52

Answers (1)

konsolebox
konsolebox

Reputation: 75588

You can replace the the newlines.

echo "$hostname, $id, ${result//$'\n'/\\n}" >> test.csv

Upvotes: 1

Related Questions