Skip to content

Instantly share code, notes, and snippets.

@JPvRiel
Last active October 10, 2016 23:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JPvRiel/b279524d3e56229a896477cb8082a72b to your computer and use it in GitHub Desktop.
Save JPvRiel/b279524d3e56229a896477cb8082a72b to your computer and use it in GitHub Desktop.
Bash String Substitution

Syntax

${varName/Pattern/Replacement}

Given a variable

$ val="test"

Replace first occurence/match

$ echo "${val/t/T}"
Test

Replace all occurences/matches

$ echo "${val//t/T}"
TesT

This can be applied to file input, e.g., replace a comma with a semicolon (a on-liner)

$ echo "a1,b2,c3" > eg.csv
$ while read line; do echo "${line//','/$'\t'}" >> eg.tsv; done < eg.csv
$ cat eg.tsv
a1	b2	c3

Note:

  • The tab needs to be escaped as $'\t', which is a quoted string-expansion construct
  • Same applies to others like newlines

Refrence:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment