Home > Mobile >  Removing newlines in a txt file
Removing newlines in a txt file

Time:11-26

I have a txt file in a format like this:

test1
test2
test3

How can I bring it into a format like this using bash?

test1,test2,test3

CodePudding user response:

Assuming that “using Bash” means “without any external processes”:

if IFS= read -r line; then
  printf '%s' "$line"
  while IFS= read -r line; do
    printf ',%s' "$line"
  done
  echo
fi

CodePudding user response:

Old answer here

TL;DR:

cat "export.txt" | paste -sd ","

CodePudding user response:

Another pure bash implementation that avoids explicit loops:

#!/usr/bin/env bash

file2csv() {
    local -a lines
    readarray -t lines <"$1"
    local IFS=,
    printf "%s\n" "${lines[*]}"
}

file2csv input.txt

CodePudding user response:

You can use awk. If the file name is test.txt then

awk '{print $1}' ORS=',' test.txt | awk '{print substr($1, 1, length($1)-1)}'

The first awk commad joins the three lines with comma (test1,test2,test3,). The second awk command just deletes the last comma from the string.

CodePudding user response:

Use tool 'tr' (translate) and sed to remove last comma:

tr '\n' , < "$source_file" | sed 's/,$//'

If you want to save the output into a variable:

var="$( tr '\n' , < "$source_file" | sed 's/,$//' )"

CodePudding user response:

Using sed:

$ sed ':a;N;$!ba;s/\n/,/g' file

Output:

test1,test2,test3

I think this is where I originally picked it up.

CodePudding user response:

If you don't want a terminating newline:

$ awk '{printf "%s%s", sep, $0; sep=","}' file
test1,test2,test3

or if you do:

awk '{printf "%s%s", sep, $0; sep=","} END{print ""}' file
test1,test2,test3

CodePudding user response:

Another loopless pure Bash solution:

contents=$(< input.txt)
printf '%s\n' "${contents//$'\n'/,}"
  • contents=$(< input.txt) is equivalent to contents=$(cat input.txt). It puts the contents of the input.txt file (with trailing newlines automatically removed) into the variable contents.
  • "${contents//$'\n'/,}" replaces all occurrences of the newline character ($'\n') in contents with the comma character. See Parameter expansion [Bash Hackers Wiki].
  • See the accepted, and excellent, answer to Why is printf better than echo? for an explanation of why printf '%s\n' is used instead of echo.
  • Related