By using ASCII code, you can replace the tab character in the same way on both macOS and Linux.
TAB="$(printf '\\\011')"
printf "hoge\tfuga\n" | sed "s/${TAB}/,/g"
sed
OS dependent (BSD sed vs GNU sed)As an example of using sed
, I often used the following script that separates tabs with commas.
# Linux
$ printf "foo\tbar\n"
foo bar
$ printf "foo\tbar\n" | sed "s/\t/,/g"
foo,bar
However, the: point_up: method does not work well on macOS.
# macOS
$ printf "foo\tbar\n"
foo bar
$ printf "foo\tbar\n" | sed "s/\t/,/g"
foo bar # <-Not changed!
Apparently this difference is due to macOS using BSD sed
and Linux using GNU sed
.
What to do with tab character replacement in BSD sed
was mentioned in a previous Qiita article: bow:
-Replace tab string with sed on macOSX -Replace tab string with sed on macOSX
(Same title, but different article)
However, since the usage of the above method is limited, I wanted to have a little more versatility, but there was the following article.
-Replace the character string with a line break with the sed command, and replace it smartly.
In the above, LF (line feed) was expressed using ASCII code as follows.
LF=$(printf '\\\012_')
LF=${LF%_}
echo "hogehoge\nfoo\nbar" | sed 's/\\n/'"$LF"'/g'
I thought that this method could be applied to tab characters as it is, and when I verified it, it worked fine.
#Horizontal tab (HT) is 011 in ASCII code
TAB="$(printf '\\\011')"
printf "hoge\tfuga\n" | sed "s/${TAB}/,/g"
You can now replace the tab character in the same way on both macOS and Linux.
# macOS
- OS: Catalina 10.15.6 19G2021 x86_64
- Kernel: 19.6.0
- Shell: zsh 5.7.1
# Linux
- OS: Linux Mint 20 x86_64
- kernel: 5.4.0-47-generic
- shell: bash 5.0.17
Recommended Posts