-1

How can I insert a tab in a text string after the occurrence of a particular word? (Suggest Unix commands or Perl script)

eg. '/home/data/samples/2014-08-05/20140805.sample.000005.eml:Subject:'

I want to insert a tab after eml:.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

1 Answers1

1

You can use sed to replace text like this:

sed -e 's/eml:/eml:\t/'

for example it works like this:

echo "/home/data/samples/2014-08-05/20140805.sample.000005.eml:Subject:" | sed -e 's/eml:/eml:\t/'

if you have a file which contains lot of these expressions:

cat <file> | sed -e 's/eml:/eml:\t/' > <new_file>
Klaus
  • 24,205
  • 7
  • 58
  • 113
  • Are you sure? Which shell expands the `\t` into tab inside single quotes? Or which version of `sed` treats `\t` as a tab? … Hmmm; I might have guessed — GNU [`sed`](http://www.gnu.org/software/sed/manual/sed.html#Escapes) manages to expand `\t` as a tab. – Jonathan Leffler Aug 11 '14 at 06:54
  • @klaus : i have a file with lots of line like the example shown. is there any way to give the filename as input so that the command runs on all the lines in the file? – user3928533 Aug 11 '14 at 07:03
  • 1
    Note that using `cat` like that is a classic [UUOC — Useless Use of `cat`](http://stackoverflow.com/questions/11710552/useless-use-of-cat/11710888#11710888). You could perfectly well use: `sed -e 's/eml:/eml:\t/' old-file > new-file`. If you want to edit the file in place and you have GNU `sed` (which this answer depends on anyway), you could use: `sed -i .bak -e 's/eml:/&\t/' old-file` which will create `old-file.bak` with the original content and leave `old-file` with the modified content. – Jonathan Leffler Aug 11 '14 at 07:28
  • Thanks Jonathan. I am very new to unix. your explanations helps a lot – user3928533 Aug 11 '14 at 07:54
  • @Jonathan: You are right. But nearly all command line tools can read and write to stdin/out. But each of the tools have an other command line option for read/modify/write to a file. So I stopped thinking about that. For a quick solution I prefer the pipes. If performance matters or I must modify data, I take a look to the man page. But only then :-) – Klaus Aug 11 '14 at 08:16
  • The only file-processing commands I can think of the do _not_ take file name arguments are `tr` and `dd`, both somewhat esoteric. I work on the assumption that every command that processes files can (should) take command line arguments that are file names until proven to the contrary. – Jonathan Leffler Aug 11 '14 at 14:13