w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Change encoding of text file (shell archive or script for antique kernel text to ASCII text, with CRLF, LF line terminators)
Unix uses a single character for line termination. If you want to convert your file with CRLF to single character termination, you can do the following: sed -e 's/<CTRL-V><CTRL_M>//' filename where <CTRL-V> is the Control key pressed with V (do not include < and > characters in the command.

Categories : Bash

Shell Script: Overwrite entire line in a text file if a partial match is found
try this sed line: sed '/ABC/s/.*/AAAAAAA/' file example: kent$ echo "ABCdefg hijklmn xxABC"|sed '/ABC/s/.*/AAAAAAA/' AAAAAAA hijklmn AAAAAAA or awk one-liner: awk '/ABC/{$0="AAAAAAA"}7' file test omitted.

Categories : Shell

submit each line to a python script using shell.
This is a shell scripting question more than it is a python one. However, I think your issue is " > test.txt" the ">" will start from a blank file each time instead of appending the results. try " >> test.txt"

Categories : Python

how to pass variable from python to shell script when shell script is getting called inside python script
You can: Step through the list, and then call mail.sh once for each file. This is the most reliable way. Convert the items in the list to a space delimited string, and then pass it in to mail.sh (assuming mail.sh is setup correctly, it should accept multiple arguments). What you cannot do is pass ['a.txt','b.txt','c.txt'] wholesale to the script.

Categories : Python

shell script: inserting a new line to a file using sed
The second example on the cited link is a solution for you < a.txt sed "/ABC$/a \ #define DEF " will produce from the a.txt #define ABC the output #define ABC #define DEF Or the 5th example from the above link < a.txt sed "/ABC$/s/$/\ #define DEF/" so, READ!

Categories : Shell

Hudson server running app engine, duplicate shell script executions result in duplicate property errors
It might be the case that the dev_appserver is already running and then you run it again with hudson job. The best way will be to stop the dev_appserver instance first and then pump it up again.

Categories : Python

shell script taking last empty line of a file also
while read LINE do [ -z "$LINE" ] && continue IMEI=$(echo $LINE | sed 's/ //g' | sed -e 's/[^ -~]//g') END_SERIAL=$(echo $IMEI | cut -c9- | sed 's/ //g' | sed -e 's/[^ -~]//g') echo "CRE:EQU,${IMEI}0,${END_SERIAL},${list},,${TODAY};" >> ${OUTFILE}i done < "${FILE_NAME}" If the line is empty, continue with the next iteration of the loop. Or have sed delete blank lines (containing blanks and tabs only) before feeding the file to the loop: sed '/^[ ]*$/d' "$FILE_NAME" | while read LINE do IMEI=$(echo $LINE | sed 's/ //g' | sed -e 's/[^ -~]//g') END_SERIAL=$(echo $IMEI | cut -c9- | sed 's/ //g' | sed -e 's/[^ -~]//g') echo "CRE:EQU,${IMEI}0,${END_SERIAL},${list},,${TODAY};" >> ${OUTFILE}i done

Categories : Linux

to insert line breaks in a file whenever a comma is encountered-Shell script
Using GNU sed: sed 's/, / /g' your.file Output: this is a file that should be added with a line break when we find a a comma. Note: the syntax above will work only on system that have the as line delimiter as Linux and the most UNIXes. If you need a portal solution in a a script then use the following expression that uses a literal new line instead of : sed 's/,[[:space:]]/ /g' your.file Thanks @EdMorten for this advice.

Categories : Shell

Shell command to iterate through every line of a text file
ack works on whole files, line-by-line. For this, just do: ack "$line" ~/temp/imageFileNames.txt And it should print out all lines that contain whatever you put for "$line". Check the docs for a better usage description than I can give: http://linux.die.net/man/1/ack

Categories : Shell

How to add text to end of file via shell script which includes double quotes
Variables need to be placed around double quotes in order for them to be expanded. You also simply have to quote them with instances of double quotes inside it with i.e. ". echo "<VirtualHost *:8888> ServerName $devname DocumentRoot "$directory" <Directory "$direcotry"> Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all </Directory> </VirtualHost>" >> /Applications/MAMP/conf/apache/vhosts.conf

Categories : Osx

Seeing if one line from file is a duplicate in another file Python
You can't just do if line in seen: to search the whole seen file for the given line. Even if you could, it would only search the rest of the file, and since you're at the end of the file, that would mean you're searching over nothing. And, even if you solved that problem, it would still require doing a linear search over the whole file for each line, which would be very slow. The simplest thing to do is to keep track of all the lines seen, e.g., with a set: with open('filetwo.txt') as f: seen = set(f) with open('fileone.txt') as fin, open('filetwo.txt', 'a+') as fout: for line in fin: if line in seen: print(line + 'is a duplicate') else: fout.write(line) seen.add(line) Notice that I'm pre-filling seen with all of the lines in

Categories : Python

How to delete a line from a text file using the line number in python
You start counting at one, but python indices are always zero-based. Start your line count at zero: for num, line in enumerate(myFile): # default is to start at 0 or subtract one from num, deleting from lines (not line): del lines[num - 1] Note that in order for your .readlines() call to return any lines, you need to either re-open the file first, or seek to the start: myFile.seek(0)

Categories : Python

how to read multiline output command line by line, in a shell script?
Maybe I found a different solution, where I can use variables also outside the loop I have to change the default IFS to newline echo Searching for android virtual devices ... IFS=$' '; for l in $(${PROGDIR}/android list avd) ; do VAR1=$(echo $l | cut -d: -f1 | sed -e 's/s*//'); #sed removes trailing blanks if [ $VAR1 == "Name" ]; then NUM_AVD=$(($NUM_AVD+1)); fi; done echo "NUM_AVD=$NUM_AVD" In this case NUM_AVD is correctly 2

Categories : Shell

AIX Shell Script - Formatting a long line of 255 Characters into a 10 line paragraph
How about this? echo "Life is not about searching for the things that could be found. It's about letting the unexpected happen. And finding things you never searched for. Sometimes, the best way to move ahead in life is to admit that you've enough" | fmt -w 30 Result: Life is not about searching for the things that could be found. It's about letting the unexpected happen. And finding things you never searched for. Sometimes, the best way to move ahead in life is to admit that you've enough

Categories : Shell

The DB2 SQL script is hanging in shell script, but working successfully in command line
Are you sure DB2 is blocking? Did you put a semicolon between commands db2 CONNECT TO ktest4 ; db2 -v -f /tmp/sql/application_system/opmdb2_privilege_remove.sql.5342 In order to trace the execution, I advise you to put some output, in order to detect where is it blocking date ; db2 -r /tmp/output.log CONNECT TO ktest4 ; db2 -r /tmp/output.log values current timestamp ; db2 -r /tmp/output.log -v -f /tmp/sql/application_system ; db2 -r /tmp/output.log values current timestamp ; db2 -r /tmp/output.log terminate With a command like this, you will save all outputs, and then you could check where is the error.

Categories : SQL

bash shell script error works on command line, not in script
Variables are supposed to contain data, and bash treats them as data. This means that shell meta-characters like quotes are also treated as data. See this article for a complete discussion on the topic. The short answer is to use arrays instead: ASCIIDOC_OPTS=( --asciidoc-opts='-a lang=en -v -b docbook -d book' ) DBLATEX_OPTS=( --dblatex-opts='-V -T db2latex' ) cmd=(a2x -v -f pdf -L "${ASCIIDOC_OPTS[@]}" "${DBLATEX_OPTS[@]}" "$1".asciidoc) # Print command in pastable format: printf '%q ' "${cmd[@]}" printf ' ' # Execute it "${cmd[@]}" Make sure not to use eval: eval "$cmd" #noooo This will appear to work with your code as you posted it, but has caveats and security problems.

Categories : Bash

write text file line by line python
If you have the Names and Locations as a list, you can do this: data = [('James','Germany'), ('Gail','US'), ('Merkel','Poland')] with open('output', 'w') as f: for name,place in data: f.write("Name=%s Location=%s " % (name, place))

Categories : Python

write a text file in Python, line by line
You have print new_str for every line in test.txt. But you only write one line to the file after the loop. Changing the code to write after each print: outf = open('result.txt', 'w') for line in fileinput.input("test.txt"): new_str = re.sub('[^a-zA-Z0-9 .]'," ", line) print new_str outf.write(new_str + ' ') outf.close() will do what you want.

Categories : Python

Perl Script only displaying first line of text file
Doesn't this: while (<F>) { print $_; { close F; close your filehandle within your while() loop i.e. after your first line ? I suspect you need something like: while(<F>) { # do something } close(F);

Categories : Perl

linux shell: prepend or append text to next line after matching line
If you're confused on the general text-piping linux applications, I would recommend going through this exercise on the Learn Linux the Hard Way course. Should take 4-5 minutes and help quite a bit.

Categories : Linux

Python script to unzip and print one line of a file
I am assuming that: You meant to have quotes around the file name in your script. You actually want the third line (as your post suggests) and not the third character (as your script suggests) In this case the following should work: import gzip data = gzip.open('pagecounts-20130601-000000.gz', 'r') data.readline() data.readline() print data.readline()

Categories : Python

how to add a new line in a text file using python without
Just change add: def add(x): nl = " " acc = ".acc" xy = x + acc exyz = xy xyz = exyz xxx = str(xyz) tf = open('accounts.dat',"a+") tf.writelines(xxx) tf.writelines(nl) # Write the newline AFTER instead of before the output tf.close() # close is a function so needs to be called by having () at the end. See the comments for what has changed.

Categories : Python

Shell Script for commenting a line
Your sed expression is written to include only the part after the ternary operator. Try: sed 's@if(a & b).*$@/* & */@' That said, I'm not sure if you really want to use regex to comment out code.

Categories : Shell

In python, how can you delete the third forth and fifth line of a text file?
Try following code: with open('input.txt') as f, open('output.txt', 'w') as fout: fout.writelines(line for lineno, line in enumerate(f, 1) if lineno not in (3,4,5))

Categories : Python

ImportError when calling python script via a shell script
I had a similar problem. It turned out that in my bash script I was running the Python script with a different version of Python than I was on the command line (my env was set up with virtualenv on Python 2.7 but I was calling the script with Python3 from the bash script). There is nothing in your snippets indicating this is the case but it is worth checking to make sure that the Python versions match up.

Categories : Python

Shell script array from command line
This tcl script uses regex parsing to extract pieces of the commandline, transforming your third argument into a list. Splitting is done on whitespaces - depending on where you want to use this may or may not be sufficient. #!/usr/bin/env tclsh # # Sample arguments: 1 2 {element1 element2} 4 # Split the commandline arguments: # - tcl will represent the curly brackets as { which makes the regex a bit ugly as we have to escape this # - we use '->' to catch the full regex match as we are not interested in the value and it looks good # - we are splitting on white spaces here # - the content between the curly braces is extracted regexp {(.*?)s(.*?)s\{(.*?)\}s(.*?)$} $::argv -> first second third fourth puts "Argument extraction:" puts "argv: $::argv" puts "arg1: $first" puts "arg2: $s

Categories : Arrays

Python's osWalk to text file? only one line being printed
You're overwriting the file in loop. Open once. import os searchFolder = '/Users/bubble/Desktop/pics' with open('/Users/bubble/Desktop/workfile.txt','w') as f: for root, dirs, files in os.walk(searchFolder): for file in files: pathName = os.path.join(root,file) print pathName print os.path.getsize(pathName) print f.write('{} '.format(pathName)) f.write('{} '.format(os.path.getsize(pathName)))

Categories : Python

Reading from a text file with python - first line being missed
Because for line in x iterates through every line. with open('test.txt') as x: for line in x: # By this point, line is set to the first line # the file cursor has advanced just past the first line print(x.read()) # the above prints everything after the first line # file cursor reaches EOF, no more lines to iterate in for loop Perhaps you meant: with open('test.txt') as x: print(x.read()) to print it all at once, or: with open('test.txt') as x: for line in x: print line.rstrip() to print it line by line. The latter is recommended since you don't need to load the whole contents of the file into memory at once.

Categories : Python

Shell: Open a file, add a line in a particular position, and replace a particular line. Is it possible?
You can use this syntax to replace the whole content of line 165 with <new content>: sed "165s/.*/<new content>/g" file In your case, and if I see it properly, you want to add content to line 163 and replace the content in line 165. So this will make the trick: $ line163='converted_time = Time.now.utc' $ line165='Date: #{converted_time.strftime("%a, %d %b %Y %X")}' $ $ sed -e "3s/.*/$line163/g" -e "5s/.*/$line165/g" file subject = subject.force_encoding('binary') body = msg.force_encoding('binary') converted_time = Time.now.utc smtp.send_mail(<<EOS, @from, @to.split(/,/)) Date: #{converted_time.strftime("%a, %d %b %Y %X")} Note I used line 3 and 5 in my case. I store the text to be used in variables and then use the sed "s/content/$variable/g" expression. The -e is

Categories : Shell

How to extract data from a text file with python script?
You could try something like this: whole_data = [] grab_lines = False with open('input','r') as atom_file: molecule_data = ['23 '] for line in atom_file: if line.startswith('coordinates'): grab_lines = True continue elif line.startswith('velocities'): grab_lines = False if molecule_data: #just checks that we aren't appending an empty list. molecule_data.append(' ') whole_data.append(molecule_data) molecule_data = ['23 '] if grab_lines: #in python 'is True' is implicit for many types. molecule_data.append(line) with open('output','w') as out_file: for molecule in whole_data: out_file.write(''.join(molecule)) I copy/past

Categories : Python

parsing inputs to shell script on command line
You need to do shift twice to get rid of both apple and orange. a single shift will only shift off one parameter, no matter where in the code it is - it's NOT related to which parameter was last accessed/assigned from. str1="$1" str2="$2"; shift ; shift or str1="$1"; shift str2="$1"; shift # Notice that due to prior shift, orange now is in $1, not $2

Categories : Bash

Replace line in variable with string in shell script
crontab -l | sed '/myscript.sh/ s/^([^ ][^ ]*) [^ ][^ ]* /1 '"$1" '/' This will show the updated contents. The pattern matches and remembers a sequence of non-blanks at the start of the line, followed by a blank, a sequence of one or more non-blanks, and another blank, and replaces that with the remembered pattern, a space, the value in $1 and a blank. If you use update.sh 7,8,9,10,11, then you get 0 7,8,9,10,11 in your crontab. You can capture the output of that command in a variable and then echo it (carefully; use double quotes) into crontab to change the actual entry. It is conceivable that you could do: crontab -l | sed '/myscript.sh/ s/^([^ ][^ ]*) [^ ][^ ]* /1 '"$1" '/' | (sleep 1; crontab) The sleep gives crontab -l a chance to fetch the current value before it is clobbere

Categories : Bash

Shell script call command line application
You can use echo, but in a pipeline. echo 1000 | java myProgram If you want to send a file, you can use cat: cat file.txt | java myProgram

Categories : Java

Linux XML Editing from Command Line / Shell Script
I wouldn't try to use sed to edit XML. Unless there is some constant to match on (that lets you decide if you are on a /1 or /2) it'll be hard (I would say impossible, but some sed guru will chime and and prove me wrong...) If you can't install stuff, something like an awk or perl script that lets you keep a minimum of state you work better than sed.

Categories : Xml

Write array to text file. Each element on a new line in Python 2.7
Use the with statement for handling files, as it automatically closes the file for you. Instead of using file.read you should loop over the file iterator itself as it returns one line at a time and is going to be more memory efficient. import sys with open(sys.argv[1]) as f, open('out.txt', 'w') as out: for line in f: if line.strip(): #checks if line is not empty out.write(line.split()[0]+' ')

Categories : Python

How to return a value from a shell script in a python script
use Subprocess.check_output instead of Subprocess.call. Subprocess.call returns return code of that script. Subprocess.check_output returns byte stream of script output. Subprocess.check_output on python 3.3 doc site

Categories : Python

Conversion of shell script to python script
It looks like you're after a templating engine, but if you wanted a straight forward, no thrills, built into the standard library, here's an example using string.Template: from string import Template with open('a.html') as fin: template = Template(fin.read()) print template.substitute(name='Bob') # <head>Bob</head> I thoroughly recommend you read the docs especially regarding escaping identifier names and using safe_substitute and such...

Categories : Python

Why does this work in the Python IDLE shell but not when I run it as a Python script from the command prompt?
As @Sukrit Kalra says, don't use datetime.py as your file name. Python is getting confused with which datetime is which (and is importing itself!). Maybe; $ mv datetime.py my_datetime.py

Categories : Python

How to pass argument in expect through command line in shell script
If you want to read from arguments, you can achieve this simply by set username [lindex $argv 0]; set password [lindex $argv 1]; And print it send_user "$username $password" That script will print $ ./test.exp user1 pass1 user1 pass1 You can use Debug mode $ ./test.exp -d user1 pass1

Categories : Linux

Passing java command line arguments in a shell script
Place your args right after the name of your main class: ... ${JVM_ARGS} com.cron.cronRunner $VAL1 $VAL2 ; EDIT: I posted this before the OP was edited to reflect the same

Categories : Java



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.