New answers tagged

1

Using sed $ printf "%s\n" * | sed 's/.csv$//; s/_/\t/g' abc q1 w1 defg q11 w2 hijk q11 w3 How it works: printf "%s\n" * prints the file names one per line s/.csv$// removes the trailing .csv. s/_/\t/g converts the _ to tabs. Using bash $ for f in *; do f="${f%.csv}"; printf "%s\n" "${f//_/$'\t'}"; done abc q1 w1 defg ...


2

You could use something like: ls -1 | tr '_' '\t'


2

With awk: #!/usr/bin/awk -f BEGIN { OFS="," }; FNR==1 { split(FILENAME,c,/[_.]/); }; { print c[1], c[2], $0 } Or as a one-liner to run on the command-line or embed in a shell script: awk -v OFS=',' 'FNR==1 {split(FILENAME,c,/[_.]/)}; {print c[1],c[2],$0}' *.csv For each input file, this splits each FILENAME into an array c, using the character ...


2

This code should do it, using sed, save it as an executable file and run with the full path to the source file as the first (and only) parameter. You can save the output to a new file if you like. #!/bin/bash FILE=$1 # check the file exists [[ -s $FILE ]] || { echo "Can't locate file '$FILE', aborting" >&2; exit 1; } # get the filename without ...


4

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)' ...


6

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.


1

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 ...


1

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 '1iabcd555.india.com' /etc/hosts


1

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


0

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



Top 50 recent answers are included