New answers tagged


I don't think this will be possible using simple tools like cut. Or, at least, not easily. Here's a Perl solution: $ perl -lane '$k=join " ",grep{/hello/}@F; print "$F[1] $k" if $k' file ID23 hello1 ID47 hello2 ID49 hello3 hello4 Which you could simplify by using grep first: $ grep hello file | perl -lane 'print "$F[1] ", join(" ", grep{/hello/}@F)' ...


If one space at the end of the line doesn't hurt you much: $ awk '{for(i=1;i<=NF;i++) if(i==2 || $i~"hello") printf $i" ";print ""}' file ID23 hello1 ID47 hello2 ID49 hello3 hello4 ID53 This doesn't assume anything about the position of the "hello" string.


In vim, or with vi on a BSD system: Use the vi command :0r !hostname Or, in its longer form, :0read !hostname You would have to press Esc first, of course. The read command usually takes a filename and inserts the contents of that file beneath the current line, but if you specify a shell command with ! in front of it, it will take the output from ...


You tagged vi however it sounds like you're looking for a CLI option. While in vi you can use shift + O to insert above and automatically add a new line and just paste your line right in. If you don't want to use an editor you can use sed. sudo sed -i '' /etc/hosts


Would this work using sed? sed -i '1 i\'$HOSTNAME'' file Using this with a file named test1 produces: $ cat test1 one two three four five Then: $ sed -i '1 i\'$HOSTNAME'' test1 leads to: $ cat test1 chris-dell one two three four five


The easiest way to do this programmatically is to write to a temporary file and then overwrite the existing one: { printf '%s\n' "$(hostname)"; cat somefile } > somefile.tmp mv somefile.tmp somefile


The other answers are all right but there's also the possibility of replacing your current delimiter in order to use cut as you wanted such as: sed "s/\/\/\//\//g" myfile.txt | cut -d/ -f2


If the delimiter is anything other than one fixed character, then cut is the wrong tool. Use awk instead. Consider this test file which has three fields: $ cat file one///two/2//two///three To print the second field and only the second field: $ awk -F/// '{print $2}' file two/2//two


A delimiter with cut is always a single character, so you can't specify "///" as a delimiter. Instead, you'd use "/" as delimiter and count the extra fields: cut -d/ -f4 myfile.txt (fields 2 and 3 are the empty fields between the slashes in "///").

Top 50 recent answers are included