Tag Info

New answers tagged

8

With tr, use the -s ("squeeze repeats") option: $ tr -s " " < file ID Name 1 a 2 b 3 g 6 f An awk solution: $ awk '{$2=$2}1' file ID Name 1 a 2 b 3 g 6 f When you change a field in record, awk rebuild $0, takes all field and concat them together, separated by OFS, which is a space by default.


3

Just use column: column -t inputFile Output: ID Name 1 a 2 b 3 g 6 f


0

I would suggest creating a script that runs as root. Have it run hourly, writing the output of 'faillog -a' to a text file everyone has access to. Then have your MOTD grep that file for the current user. This would avoid having to make any unnecessary permissions changes or granting someone sudo access that doesn't need it.


2

Just pipe through a while loop: git diff --name-only develop | grep coffee$ | while IFS= read -r file; do ./node_modules/.bin/coffeelint "$file" done


0

Few comments about your code: If you want to easily insert configuration from "replacements" if it doesn't exist, consider iterating each "replacement" over the lines of the file instead of each line of the file over "replacements". This way, if you don't find any replacement key in the lines, construct and write a new configuration line. I would rather ...


2

I would probably do something like this: # as proposed by csny, only open file quickly (file is closed after with statement) with open('sysctl.conf') as infile: infilelines = infile.readlines() outfile = open('sysctl.conf.new', 'w') replacements = {'Net.ipv4.icmp_echo_ignore_all' :'1', 'Net.ipv4.icmp_echo_ignore_broadcasts' :'1', ...


0

With zsh: print -r -- **/*.csv(D:a:q) Note that some characters (like newline, tab or non-printable ones) are rendered with the $'...' notation which may be a problem for you. Another approach is: print -r -- *.csv(e/'REPLY=${(qq)REPLY:a}'/) Where all the file paths are single-quoted.


0

There is a good answer here in this stackoverflow question For example to extend an alias of 'ls' by adding a '-o' you would do eval "$(alias -p|grep '^alias ls='|sed "s/'$/ -o'/")"


3

For passing file paths as arguments to a command, find does this on its own with its -exec option without any xargs trickery: find /home/user -name '*.csv' -exec yourcommand '{}' + That will find every file called *.csv in /home/user and then execute yourcommand /home/user/a\ b.csv /home/user/my\ dir/c\ d\$2.csv ... with all of the found files as ...


2

If you just installed it it's likely that your shell has cached the old path. Use: hash -r to clear the command hash table and then try running the command again.


5

An ugly way of doing this (i.e. causing a function call in shell based on output from awk) could look like this: awk -F '\t' ' FNR < 2 {next} FNR == NR { for (i=2; i <= NF; i++) { if (($i == 1) || ($i == 4)) printf "retrieve %s\n", $i if (($i == 2) || ($i == 2)) printf "retrieve2 ...


1

A separate printf can do the 0 padding with %0Xd when needed. zero_pad(){ # zero_pad <string> <length> [ ${#1} -lt $2 ] && printf "%0$(($2-${#1}))d" '' printf "%s\n" "$1" } . $ zero_pad "" 5 00000 $ zero_pad "over" 5 0over $ zero_pad "under" 4 under $ zero_pad "exact" 5 exact $ zero_pad " space" 7 0 space


0

Here is a Bash Scripting Tutorial which is good if you are a beginner. If you are new to the Linux command line here is a Linux tutorial which is also good for the beginner.


6

You should use -v option of awk: awk -F',' -v accNum="$1" '$1 == accNum {print $3,$2}' With $1 in double quote, the shell will handle all its special character ( if has ) for you.


2

Your script already practically does the job without any awk at all: while IFS=, read -r num last first do [ $((num==accountNum)) -eq 1 ] && printf '%s.%s\n' "$first" "$last" done < Accounts I'm not suggesting that this is a better or more efficient solution than using awk alone, but if you want the while...read loop, this ...


2

You have: accountNum=$1 awk -F',' '{ if($1==accountNum) { print $3.$2 } }' Accounts How does the shell variable accountNum get into awk? It doesn't: you need to provide its value to awk explicitly. You can use: awk -F',' '{ if($1=='"$accountNum"') { print $3.$2 } }' Accounts which leaves single quotes and has the shell substitute the value of its ...


-1

For a little fun and edification, here is a shell that is sh-compatible: cat /*dev/null; echo "Happy New Year"\! cat <<c*/ /*dev/null | cat > /dev/null c */ () {} /* c */ main() { cat(); printf("Happy New Year!\n"); } /* 17 format('Happy New Year!') write (6,17) stop end c*/ You can run it with sh, but also with csh, ...


20

why are there so many "sh compatible" shells The Bourne shell has been with us since 1977, released as part of Unix V7. Since pretty much every Unix and Unix-like system descends from V7 Unix — even if only spiritually — the Bourne shell has been with us "forever."1 The Bourne shell actually replaced an earlier shell, retronymed the ...


7

"sh compatible" refers to POSIX sh, the basic shell that is required to exist on all compatible systems. A sh-compatible script should work on any POSIX-compatible machine. The reason it's necessary to say so is that commonly /bin/sh is a symlink to /bin/bash, which has let some Bashisms slip into scripts that declare themselves to use sh with #!/bin/sh. ...


12

In most shells including bash, pwd is a shell builtin: $ type -a pwd pwd is a shell builtin pwd is /bin/pwd If you use /bin/pwd, you must use the -L option to get the same result as builtin pwd: $ ln -s . test $ cd test && pwd /home/cuonglm/test $ /bin/pwd /home/cuonglm $ /bin/pwd -L /home/cuonglm/test By default, /bin/pwd ignores symlinks and ...


3

I may be missing something but I don't understand why you are fiddling with grep in the first place. That's what pgrep is for: #!/bin/sh # chkconfig: 123456 90 10 workdir=/usr/local/bin/Foo start() { cd $workdir /usr/bin/python26 $workdir/Bar.py & echo "FooBar started." } stop() { pid=`pgrep -f '/Bar.py$'` echo $pid kill $pid ...


0

Here's a way: watch -n 1 'date' &>/dev/null & Since you background the process, we can assume you don't need the terminal display and you are fine redirecting to a file. If you do that you will be able to background watch without issue. sleep, as suggested by Michael Mrozek, will slowly lag which can be undesirable. Aside from a convoluted ...


2

As @Gnouc has already noted, you're halfway there already: line='some chars' printf '%0'$((20-${#line}))'d%s\n' 0 "$line" ###OUTPUT### 0000000000some chars Of course, then you still wind up with a 0 even if line is longer than 20 chars, and that's only if printf doesn't fail with an error because it doesn't properly handle the -dash in its format string ...


2

The portable way to do this - and the more efficient way - is with addresses. You can do this: printf %s\\n cat dog pear banana cat dog | sed '/cat/!{/dog/!b};cBear' In this way if the line does not contain the string cat and does not contain the string dog sed branches out of the script, autoprints its current line and pulls in the next to begin the next ...


5

By default sed uses POSIX Basic Regular Expressions, which don't include the | alternation operator. Many versions of sed, including GNU and FreeBSD, support switching into Extended Regular Expressions, which do include | alternation. How you do that varies: GNU sed uses -r, while FreeBSD, NetBSD, OpenBSD, and OS X sed use -E. Other versions mostly don't ...


3

This happends because (a|b) is a regular expression use -r option to deal with this: echo 'cat dog pear banana cat dog'|sed -r 's/cat|dog/Bear/g' from sed manpage: -r, --regexp-extended use extended regular expressions in the script.


0

Awk isn't going to make your life easier. You can use the suffix removal syntax: ${x%.*} is the value of the variable x with the shortest suffix of the form .* removed. for x in *.txt.*.*; do mv "$x" "/other/directory/${x%.*}" done


2

Just do the padding manually. I don't think there's a more straightforward solution if you stick to POSIX tools. while [ ${#line} -lt 20 ]; do line=0$line done or n=${#line} while [ $n -lt 20 ]; do printf '0' n=$((n-1)) done printf "$line\n" In zsh, of course, there's syntax for that. Unlike the snippets above, this one truncates the string if ...


-1

This should do the job: rename -vn 's/.[0-9,:,_]+$//' /path/to/* Call the command without the -n switch when you see that the file get renamed correctly in the output. rename will print the filenames (-v). With this command everything after the last point (.) will be deleted out of the filename from every (*) file in the folder /path/to/. Output in my ...


-1

I have a less complicated answer, and surely not a keylogger. I don't get your point of being server log independent (this means that all the actions need to be taken to the server and all logs are server side logs), and thus I thought that a good idea is to pass to system wide bashrc a prompt command like: PROMPT_COMMAND='history -a >(tee -a ...


2

If you can use perl: $ perl -e 'print sprintf "%020s\n","shortstring"' 000000000shortstring For more general: $ perl -e 'print sprintf "%020s\n",shift' shortstring 000000000shortstring $ perl -e 'print sprintf "%020s\n", $_ for @ARGV' shortstring qwerty 000000000shortstring 00000000000000qwerty Note Some platform can be formated output string with ...


1

%s is a string formatting specification. Zero padding is only defined to exist for numeric conversions: 0 For d, i, o, u, x, X, a, A, e, E, f, F, g, and G conversion specifiers, leading zeros (following any indication of sign or base) are used to pad to the field width ... For other conversions, the behavior is undefined. If your $line is a number, ...


5

I assume you've inadvertently trimmed the important part of your command lines out here: the URLs in question contain a ? character (or a *). ? and * are special glob matching characters to the shell. ? matches a single character in a filename, and * matches many. When zsh says: zsh: no matches found: http://myvideosite.com?video=123 it's telling you that ...


0

# rm /etc/bash.bashrc # apt-get -o Dpkg::Options::="--force-confmiss" install --reinstall bash I hit those two commands up Reinstallation of bash is not possible, it cannot be downloaded. I am on a ubuntu 14.04


2

In a shell script, you call the getopts function in a loop. There is a code example in the dash manual. Note that your Python code is not correct except in extremely simple cases. It detects an argument -v anywhere on the line, even if it's the argument of another option or after non-option arguments. The correct way to parse options in Python is with ...


1

Something like: for i in "$@" do [ "$i" = -v ] && verbose=1 done


3

Your problem is that the script in your .../bin directory is execed in another shell environment - its environment does not survive its execution and so the x() { ... ; } definition does not survive into the current shell environment when it completes. When you . ./somescript.sh (or source in some shells such as bash and zsh) the current shell reads the ...


2

More elegant? No Shorter? Yes :) #!/bin/bash read string if [ ${#string} -ge 5 ]; then echo "error" ; exit else echo "done" fi


1

In bash, the argument to the last command you ran is saved as !$. This is documented in man bash: ! Start a history substitution, except when followed by a blank, newline, carriage return, = or ( (when the extglob shell option is enabled using the shopt builtin). [...] $ The last argument. So, you could do $ ...


2

If your concern includes the retyping of ~/test-tmp, you can do the following to shorten and combine the commands into a one-liner: D=~/test-tmp; mkdir $D; cp * $D; cd $D Please note that if your path includes spaces, you have to quote the assignment and where you use the variable: D="~/test tmp"; mkdir "$D" ; cp * "$D"; cd "$D"


2

You mean like this? mkdir ~/test-tmp && cp * ~/test-tmp && cd ~/test-tmp or function mm() { local dir=$1 if [ ! -z "$dir" ] then mkdir ~/${dir} && cp * ~/${dir} && cd ~/${dir} fi }


2

the file's content is shown as empty as long as the file is opened for writing by Bash. That's not exactly what's happening. What's happening is that the task buffers its output — it is accumulated in memory for a while, then written to the file in chunks. The in-memory buffer has a fixed size of a few kilobytes. This is done for performance, as each ...


1

This string literal in awk "echo \"select * from abc limit 1;\"| impala-shell|grep -Eo \" a-[0-9]-[0-9]* \| HS[0-9] \| [0-9]* \| [0-9]* \" " represents the following string value: echo "select * from abc limit 1;"| impala-shell|grep -Eo " a-[0-9]-[0-9]* | HS[0-9] | [0-9]* | [0-9]* " Backslash followed by another character which is not a letter or ...


3

Use: mimeopen -a 0001.jpg -a will first Ask you to choose, not run it. Please choose an application 1) Wine Internet Explorer (wine-extension-jfif) 2) Wine Internet Explorer (wine-extension-jpe) 3) Firefox Web Browser (firefox) 4) Luminance HDR (luminance-hdr) 5) ImageMagick (display) (display.im6) 6) Image Viewer (eog) 7) Shutter (shutter) 8) ...


3

This is a bit of a complicated question. I'll try to answer your questions in turn, but first a general description: The scrollback buffer is implemented by your terminal emulator (xterm, Konsole, GNOME Terminal). It contains all the text that has been displayed on the screen, including both standard output and standard error from every program you run in ...


8

mimeopen -a 'picture.jpg' This is what you need It will give you output like this Please choose an application 1) Shotwell Viewer (shotwell-viewer) 2) Firefox Web Browser (firefox) 3) Image Viewer (eog)


1

Most easy to understand: grep -A 1000 '%packages' xx | grep -B 1000 '%end' First part searches for %packages and prints 1000 lines (including the matched line) A fter it. Second part after the pipe: Searches for %end and prints all 1000 lines (including the matched line) B efore. If the file has more than 1000 lines, change the 1000 to a greater number. ...


2

In addition to awk, another solution to consider is sed: sed -n '/%packages/,/%end/ w file2' file1 breakdown by order of appearance: sed itself, obviously, followed by an opening '. This tells sed everything from this point until closing ' is an argument/command to sed itself. Everything after that is input (or output if using redirection >file) -n ...


0

Here are a couple of shameless rip-offs of LatinSuD’s answer that handle floating point.  You’ll notice that his answer boasts “No external programs are required.”  This one uses the calculator program, bc, as he suggested: #!/bin/bash # The comparing function function compareInterval { t1=$1 t2=$2 shift 2 while (( "$2" )) do # if (( $t1 >= ...


4

To copy all lines between %packages and %end from file1 into file2: awk '$1=="%end" {f=0;next} f{print;next} $1=="%packages" {f=1}' file1 >>file2 This solution is designed to remove the lines %packages and %end. (If you want those lines to be transferred as well, there is an even simpler solution below.) Since awk implicitly loops over all lines ...



Top 50 recent answers are included